#include <stdio.h>
#include <string.h>
#include "invertword.h"

static void getword(char **str,
		    char **pbegin,
		    char **pend) {
  char *p;
  int word;

  if (NULL == *str || '\0' == **str)
    return;

  for (p = *str, word = 0; *p != '\0'; ++p) {
    if (' ' == *p && 0 == word) {
      continue;
    } else if (*p != ' ' && 0 == word) {
      word = 1;
      *pbegin = p;
    } else if (*p == ' ' && 1 == word) {
      *pend = p - 1;
      *str = p;
      return;
    }
  }
  
  if ('\0' == *p && *(p - 1) != ' ')
    *pend = p - 1;
  
  *str = p; 
}

static void inverse(char *begin, char *end) {
  char ch;
  
  if (begin == end)
    return;
  while (begin < end) {
    ch = *begin;
    *begin++ = *end;
    *end-- = ch;
  }
}

void invertword(char *str) {
  char *p = str, *pb = NULL, *pe = NULL;
  
  if (NULL == str)
    return;

  while(*p != '\0') {
    pb = pe = NULL;
    getword(&p, &pb, &pe);
    inverse(pb, pe);
  }

  inverse(str, p-1);
}



int main(int argc, char *argv[]) {
  char str[1024];
  if (argc != 2)
    strcpy(str, "I am a student.");
  else
    strcpy(str, argv[1]);
  
  printf("b: %s\n", str);
  invertword(str);
  printf("e: %s\n", str);
  
  return 0;
}
